package com.jydd.plug_in_study;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.jydd.plug_in_study.util.Util;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

/**
 * created by 韦敏敏
 * on 2019/12/27
 */
public class LocalBroadcaseReceiverActivity extends AppCompatActivity {
    public static final String LOCAL_BROADCAST_ACTION = "com.ddch.localbroadcast";
   private LocalBroadcastManager localBroadcastManager;
   private MyReceiver mMyReceiver;
   private TextView tvContent;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_broadcast_receiver);
        tvContent = findViewById(R.id.tvContext);
        // 初始化广播接收器相关
        initReceiver();
        findViewById(R.id.sendBroadcast).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(LOCAL_BROADCAST_ACTION);
                intent.putExtra("nameone", "我是本地广播");
                localBroadcastManager.sendBroadcast(intent);
            }
        });
    }

    private void initReceiver() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter mIntentFilter = new IntentFilter("com.ddch.localbroadcast");
         mMyReceiver = new MyReceiver();
        // 绑定
        localBroadcastManager.registerReceiver(mMyReceiver, mIntentFilter);
    }
    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(LOCAL_BROADCAST_ACTION.equals(action)){
                String valueOne = intent.getStringExtra("nameone");
                if(!TextUtils.isEmpty(valueOne)){
                    tvContent.setText(valueOne);
                }
            }
            Util.showToast(LocalBroadcaseReceiverActivity.this, "action : " + action);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解绑
        localBroadcastManager.unregisterReceiver(mMyReceiver);
    }
}
